package com.ettractions.kiosk.mediators
{
	import com.ettractions.kiosk.Kiosk;
	import com.ettractions.kiosk.components.ScreenSaver;
	import com.ettractions.kiosk.events.BrochureSelectEvent;
	import com.ettractions.kiosk.events.ViewEvent;
	import com.greensock.TweenLite;
	
	import flash.display.BitmapData;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import mx.core.IVisualElement;
	
	import org.robotlegs.mvcs.Mediator;
	
	import spark.components.DataGroup;
	
	public class ScreenSaverMediator extends Mediator
	{
		public static const MAGNIFYING_GLASS_TWEEN_DURATION:uint = 2;
		
		[Inject]
		public var view:ScreenSaver;
		
		private var _magnifyingGlassTween:TweenLite;
		
		private var _appWidth:uint;
		
		private var _appHeight:uint;		
		
		override public function onRegister():void
		{
			_appWidth = view.parentApplication.width;
			_appHeight = view.parentApplication.height;
			
			view.visible = false;			
			
			eventDispatcher.addEventListener(ViewEvent.GRID_PAGE_CHANGE, handleGridPageChange);
			eventDispatcher.addEventListener(BrochureSelectEvent.BROCHURE_SELECTED, handleBrochureSelected);
		}
		
		private function moveMagnifyingGlass():void
		{
			var group:DataGroup = Kiosk(view.parentApplication).thumbnailGrid.list.dataGroup;
			var index:uint = Math.floor(group.numElements * Math.random());
			var element:IVisualElement = group.getElementAt(index);
			var coords:Point = group.localToGlobal(new Point(element.x + (element.width / 2), element.y + (element.height / 2)));
			
			_magnifyingGlassTween = new TweenLite(
				view.graphic,
				MAGNIFYING_GLASS_TWEEN_DURATION,
				{
					x:coords.x,
					y:coords.y,
					onUpdate:handleTweenUpdate,
					onComplete:handleTweenComplete
				}
			);
			
			_magnifyingGlassTween.play();
		}
		
		private function handleGridPageChange(event:ViewEvent):void
		{
			var bitmapData:BitmapData = new BitmapData(_appWidth, _appHeight, false);
			
			view.visible = false;
			
			bitmapData.draw(view.root, null, null, null, new Rectangle(0, 0, _appWidth, _appHeight), true);
			
			view.image.source = bitmapData;
			
			view.visible = true;
			
			moveMagnifyingGlass();
		}
		
		private function handleBrochureSelected(event:BrochureSelectEvent):void
		{
			view.visible = event.index == -1;
			
			if (view.visible)
				moveMagnifyingGlass();
		}
		
		private function handleTweenUpdate():void
		{
			view.image.x = -(((_appWidth * view.image.scaleX) - _appWidth) * (view.graphic.x / _appWidth));
			view.image.y = -(((_appHeight * view.image.scaleY) - _appHeight) * (view.graphic.y / _appHeight));
		}
		
		private function handleTweenComplete():void
		{
			if (view.visible)
				moveMagnifyingGlass();
		}
	}
}